/*
 * @(#) CategoriaMgr.java        15/05/2008
 *
 * Proyecto: Gilabert
 *
 * Copyright (c) 2007 kaizolo
 * Todos los derechos reservados.
 *
 */
package com.kaizolo.gilabert.admin.managers;

import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.kaizolo.gilabert.utils.DBOperations;
import com.kaizolo.gilabert.utils.DBOperationsException;

/**
 * Manager de Categoria
 *
 * @author manolo
 *
 * @version 15/05/2008 manolo
 *          Manager de Categoria
 *
 */
public class CategoriaMgr {

	public static final String TABLA_CATEGORIA = "categorias";
	
	private final String SQL_ID_LIBRE = "SELECT t1.id FROM " + TABLA_CATEGORIA + " t1 " +
	                                    "WHERE NOT EXISTS (SELECT t2.id FROM " + TABLA_CATEGORIA + " t2 WHERE t2.id = t1.id + 1) " +  
                                              "AND EXISTS (SELECT t3.id FROM " + TABLA_CATEGORIA + " t3 WHERE t3.id = 1) " +
	                                    "ORDER BY t1.id";
	
	/**
	 * Devuelve un id libre en la BD
	 * @return - BigInteger
	 * @throws DBOperationsException
	 * @throws SQLException
	 */
	//public long getIdLibre() throws DBOperationsException {
	public BigInteger getIdLibre() throws DBOperationsException {
		DBOperations.getInstance();
		ArrayList returned = DBOperations.executeQuery(SQL_ID_LIBRE);
		ResultSet res = (ResultSet)returned.get(1);
		try {
			if(res.next()) {
				return BigInteger.valueOf(res.getLong(1) + 1);
			} else {
				return BigInteger.valueOf(1);
			}
		} catch (SQLException e){
			e.printStackTrace();
			throw new DBOperationsException(e.getMessage());
		} finally {
			DBOperations.closeConnection(returned);
		}
	}//public long getIdLibre() 
	
}